<template>
  <view class="video-page">
    <!-- 视频容器 -->
    <view class="video-container">
      <video 
        id="videoPlayer" 
        class="video-player"
        :src="videoUrl"
        :controls="showControls" 
        :autoplay="autoplay"
        :show-progress="true" 
        :vslide-gesture="true"
        :enable-play-gesture="true" 
        :show-center-play-btn="false"
        :show-fullscreen-btn="true"
        :show-play-btn="true"
		:show-background-playback-button="false"
        :object-fit="objectFit"
        @play="handlePlay" 
        @pause="handlePause" 
        @ended="handleEnded"
        @fullscreenchange="handleFullscreenChange"
        @canplay="handleCanPlay"
        @error="handleError"
      >
        <!-- 自定义播放按钮 -->
        <view 
          v-if="!playerState.isPlaying && !playerState.hasError && playerState.canPlay" 
          class="custom-play-btn"
          @click.stop="togglePlay"
        >
          <image 
            class="play-icon" 
            src="../../pagesC/static/img/play.png"
          />
        </view>

        <!-- 错误状态 -->
        <view 
          class="error-overlay"
		  v-if="playerState.hasError"
        >
          <view class="error-content">
			<u-icon  class="error-icon"  name="error-circle-fill" color="#ff0000" size="28"></u-icon>
            <text class="error-text">{{ errorMessage }}</text>
            <button 
              class="retry-btn" 
              @click="retryLoad"
            >
              重试
            </button>
          </view>
        </view>
      </video>
    </view>

    <!-- 视频信息栏 -->
    <view 
      v-if="showVideoInfo" 
      class="video-info"
    >
      <view class="info-item">
        <text class="label">监控点：</text>
        <text class="value">{{ videoInfo.name || '未知' }}</text>
      </view>
      <view class="info-item">
        <text class="label">时间：</text>
        <text class="value">{{ currentTime }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

// Props定义
const props = defineProps({
  autoplay: {
    type: Boolean,
    default: true
  },
  showControls: {
    type: Boolean,
    default: true
  },
  showVideoInfo: {
    type: Boolean,
    default: false
  },
  objectFit: {
    type: String,
    default: 'fill'
  }
})

// 响应式数据
const videoUrl = ref('')
const videoContext = ref(null)
const currentTime = ref('')
const timeInterval = ref(null)
const errorMessage = ref('视频加载失败')

// 视频信息
const videoInfo = reactive({
  name: '',
  location: '',
  deviceId: ''
})

// 播放器状态
const playerState = reactive({
  isPlaying: false,
  isFullscreen: false,
  hasError: false,
  canPlay: false
})

// 页面加载
onLoad((options) => {
  initializeVideo(options)
  updateCurrentTime()
  startTimeUpdate()
})

onShow(() => {
  uni.setKeepScreenOn({ keepScreenOn: true })
})

onUnmounted(() => {
  cleanup()
})

// 初始化视频
function initializeVideo(options) {
  try {
    if (options.url) {
      videoUrl.value = decodeURIComponent(options.url)
	  videoInfo.name = options.name
    } else {
      videoUrl.value = ''
    }
	// https://open.ys7.com/v3/openlive/FQ0360647_13_1.m3u8?expire=1776819645&id=834715341937106944&t=15ed51c6a94b55c7cae2ff3c622669aef37dab34a506e74d5559c95ff565cc18&ev=100
    // 重置状态
    playerState.hasError = false
    playerState.canPlay = false
    
    // 初始化视频上下文
    uni.nextTick(() => {
      videoContext.value = uni.createVideoContext('videoPlayer')
    })
  } catch (error) {
    console.error('初始化视频失败:', error)
    handleError({ detail: { errMsg: '初始化失败' } })
  }
}

// 事件处理函数
function handleCanPlay() {
  console.log('视频可以播放')
  playerState.canPlay = true
  playerState.hasError = false
}

// 视频开始播放
function handlePlay() {
  console.log('视频开始播放')
  playerState.isPlaying = true
  uni.setKeepScreenOn({ keepScreenOn: true })
}

// 视频暂停
function handlePause() {
  console.log('视频暂停')
  playerState.isPlaying = false
}

// 视频播放结束
function handleEnded() {
  console.log('视频播放结束')
  playerState.isPlaying = false
}

// 全屏状态改变
function handleFullscreenChange(event) {
  playerState.isFullscreen = event.detail.fullScreen
}

// 错误处理函数
function handleError(event) {
  console.error('视频播放错误:', event.detail)
  
  playerState.hasError = true
  
  // 根据错误类型设置不同的错误信息
  const errMsg = event.detail?.errMsg || ''
  if (errMsg.includes('network')) {
    errorMessage.value = '网络连接失败，请检查网络'
  } else if (errMsg.includes('decode')) {
    errorMessage.value = '视频格式不支持'
  } else if (errMsg.includes('timeout') || errMsg.includes('超时')) {
    errorMessage.value = '加载超时，请重试'
  } else {
    errorMessage.value = '视频加载失败，请重试'
  }
  
  uni.showToast({
    title: errorMessage.value,
    icon: 'none'
  })
}

// 切换播放状态
function togglePlay() {
  if (!playerState.canPlay || playerState.hasError) return
  
  if (playerState.isPlaying) {
    pause()
  } else {
    play()
  }
}

// 播放视频
function play() {
  if (videoContext.value && playerState.canPlay) {
    videoContext.value.play()
  }
}

// 暂停视频
function pause() {
  if (videoContext.value) {
    videoContext.value.pause()
  }
}

// 重试加载
function retryLoad() {
  playerState.hasError = false
  
  // 重新设置视频源
  const currentUrl = videoUrl.value
  videoUrl.value = ''
  
  uni.nextTick(() => {
    videoUrl.value = currentUrl
  })
}

// 更新当前时间
function updateCurrentTime() {
  const now = new Date()
  currentTime.value = now.toLocaleString()
}

function startTimeUpdate() {
  timeInterval.value = setInterval(updateCurrentTime, 1000)
}

function cleanup() {
  if (timeInterval.value) {
    clearInterval(timeInterval.value)
  }
  uni.setKeepScreenOn({ keepScreenOn: false })
}
</script>

<style lang="scss" scoped>
.video-page {
  width: 100vw;
  height: 100vh;
  background-color: #000;
  display: flex;
  flex-direction: column;
}

.video-container {
  flex: 1;
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-player {
  width: 100%;
  background-color: #000;
}

.custom-play-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10rpx);

  .play-icon {
    width: 64rpx;
    height: 64rpx;
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.7);
  z-index: 20;

  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid rgba(255, 255, 255, 0.3);
    border-top: 4rpx solid #ffffff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    color: #ffffff;
    font-size: 28rpx;
    margin-top: 20rpx;
  }
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.8);
  z-index: 20;

  .error-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    height: 180rpx;

    .error-icon {
      margin-bottom: 20rpx;
    }

    .error-text {
      color: #ffffff;
      font-size: 28rpx;
    }

    .retry-btn {
      border: none;
      border-radius: 6rpx;
      font-size: 20rpx;
      color: #323233;
      background-color: #fff;
      border-color: #ebedf0;
      border-width: 1px;
      border-style: solid;
    }
  }
}

.video-info {
  background: rgba(0, 0, 0, 0.8);
  padding: 20rpx 30rpx;
  padding-bottom: env(safe-area-inset-bottom);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .info-item {
    display: flex;
    align-items: center;

    .label {
      color: #999;
      font-size: 24rpx;
      width: 100rpx;
    }

    .value {
      color: #ffffff;
      font-size: 24rpx;
      // 溢出显示省略号
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 300rpx;
    }
  }
}

@keyframes spin {
  0% { 
    transform: rotate(0deg); 
  }
  100% { 
    transform: rotate(360deg); 
  }
}

// 适配不同屏幕
@media screen and (orientation: landscape) {
  .video-info {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 100;
  }
}

</style>
